package com.hcm.kernel.wechat;

import com.alibaba.fastjson.JSON;
import com.hcm.kernel.util.SystemConfig;
import com.hcm.kernel.wechat.util.HttpUtil;
import com.hcm.kernel.wechat.util.TokenCache;
import org.apache.http.entity.ByteArrayEntity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by zhangzunwei on 15/6/3.
 */
public class QRCodeAPI {

    public static String getTicket(String openid){
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s";
        if(!SystemConfig.getBoolean("use_default_interface"))
            url = SystemConfig.getString("qrcode_ticket");
        url = String.format(url, TokenCache.getAccessToken());

        String param = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+openid+"\"}}}";
        ByteArrayEntity byteArrayEntity = new ByteArrayEntity(param.getBytes());
        String json = HttpUtil.execute(url, byteArrayEntity);
        String ticket = JSON.parseObject(json).get("ticket").toString();
        return ticket;
    }

    public static String createQRCode(){
        String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s";
        if(!SystemConfig.getBoolean("use_default_interface"))
            url = SystemConfig.getString("qrcode");

        url = String.format(url, getTicket("op2cJuIiKxdzquNUhiu2k9VCwNqE"));
        try {
            url = URLEncoder.encode(url,"utf-8");
        } catch (UnsupportedEncodingException e) {
        }

        return HttpUtil.execute(url,null);
    }

    public static void main(String[] args) {
        QRCodeAPI.createQRCode();
    }
}
